<template>
  <div class="personal-bill-container">
    <h2>个人账单记录</h2>
    <div class="filter-buttons">
      <!-- <el-button @click="resetDateFilter">重置日期筛选</el-button> -->
      <el-button @click="clearFilter">重置所有筛选</el-button>
      <el-button type="primary" @click="refreshData">刷新数据</el-button>
      <el-button type="success" @click="openAddDialog">添加</el-button>
    </div>
    <div v-loading="loading" class="loading-container">
      <el-table
        ref="tableRef"
        row-key="id"
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        element-loading-text="加载中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.1)"
        @cell-click="handleCellClick"
      >
        <el-table-column
          prop="bookDate"
          label="日期"
          sortable
          width="140"
          :filters="dateOptions"
          :filter-method="filterHandler"
        />
        <el-table-column prop="type" label="类型" width="100" :filters="typeFilters" :filter-method="filterType">
          <template #default="scope">
            <el-tag :type="scope.row.type === 1 ? 'danger' : 'success'">
              {{ scope.row.type === 1 ? '支出' : '收入' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="category"
          label="消费类别"
          width="160"
          :filters="categoryFilters"
          :filter-method="filterCategory"
        >
          <template #default="scope">
            <el-tag :type="getCategoryType(scope.row.category)">
              {{ scope.row.category }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="金额" width="120" :formatter="formatCurrency" sortable />
        <el-table-column prop="source" label="支付方式" width="140" />
        <el-table-column label="备注" width="180">
          <template #default="scope">
            <span v-if="scope.row.remark">{{ scope.row.remark }}</span>
            <span v-else class="text-gray-400">无备注</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button
              size="small"
              type="danger"
              :loading="deletingIds.includes(scope.row.id)"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="tableData.length === 0 && !loading" class="empty-data">
      <el-empty description="暂无账单记录" />
    </div>

    <el-dialog v-model="dialogVisible" title="添加账单记录" @open="onDialogOpen">
      <el-form ref="addFormRef" :model="newRecord" :rules="formRules" label-width="100px">
        <el-form-item label="日期" prop="bookDate">
          <el-date-picker
            v-model="newRecord.bookDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="newRecord.type">
            <el-radio :value="1">支出</el-radio>
            <el-radio :value="0">收入</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="消费类别" prop="category">
          <el-select v-model="newRecord.category" placeholder="选择类别">
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="price">
          <el-input v-model.number="newRecord.price" type="number" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="支付方式" prop="source">
          <el-input v-model="newRecord.source" placeholder="请输入支付方式" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="newRecord.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeAddDialog">取消</el-button>
          <el-button type="primary" :loading="isAdding" @click="handleAddRecord">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增：编辑账单弹窗 -->
    <el-dialog v-model="editDialogVisible" :key="editRecord.id" title="编辑账单记录" @open="onEditDialogOpen">
      <el-form ref="editFormRef" :model="editRecord" :rules="formRules" label-width="100px">
        <el-form-item label="日期" prop="bookDate">
          <el-date-picker
            v-model="editRecord.bookDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="editRecord.type">
            <el-radio :value="1">支出</el-radio>
            <el-radio :value="0">收入</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="消费类别" prop="category">
          <el-select v-model="editRecord.category" placeholder="选择类别">
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="price">
          <el-input v-model.number="editRecord.price" type="number" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="支付方式" prop="source">
          <el-input v-model="editRecord.source" placeholder="请输入支付方式" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editRecord.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeEditDialog">取消</el-button>
          <el-button type="primary" :loading="isEditing" @click="handleEditRecord">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted, watch, nextTick } from 'vue'
  import type { TableColumnCtx, TableInstance, FormInstance } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { getBookDataList, deleteBookRecord, addBookRecord, updateBookRecord } from '@/api/userApi'

  // 状态管理
  const tableRef = ref<TableInstance>()
  const addFormRef = ref<FormInstance>()
  const editFormRef = ref<FormInstance>()
  const tableData = ref([] as any[])
  const loading = ref(false)
  const userId = ref('')
  const dialogVisible = ref(false) // 管理对话框显示状态
  const editDialogVisible = ref(false)
  const deletingIds = ref<number[]>([])
  const isAdding = ref(false)
  const isEditing = ref(false)

  // 筛选选项
  const dateOptions = ref([] as any[])
  const categoryFilters = ref([
    { text: '餐饮', value: '餐饮' },
    { text: '交通', value: '交通' },
    { text: '购物', value: '购物' },
    { text: '娱乐', value: '娱乐' },
    { text: '住房', value: '住房' },
    { text: '其他', value: '其他' },
  ])
  const typeFilters = ref([
    { text: '支出', value: 1 },
    { text: '收入', value: 0 },
  ])

  // 添加记录表单数据
  const newRecord = reactive({
    bookDate: new Date(),
    userId: '',
    type: 1,
    category: '餐饮',
    description: '',
    price: 0,
    source: '其它',
    remark: '',
  })

  // 编辑记录表单数据
  // 编辑记录表单数据
  interface EditRecord {
    id: number
    bookDate: Date
    userId: string
    type: number
    category: string
    description: string
    price: number
    source: string
    remark: string
  }
  const editRecord = reactive<EditRecord>({
    id: 0,
    bookDate: new Date(),
    userId: '',
    type: 1,
    category: '餐饮',
    description: '',
    price: 0,
    source: '其它',
    remark: '',
  })

  // 表单验证规则
  const formRules = reactive({
    bookDate: [{ required: true, message: '请选择日期', trigger: 'change' }],
    type: [{ required: true, message: '请选择类型', trigger: 'change' }],
    category: [{ required: true, message: '请选择消费类别', trigger: 'change' }],
    price: [
      { required: true, message: '请输入金额', trigger: 'blur' },
      { type: 'number', message: '金额必须为数字值', trigger: 'blur' },
      {
        validator: (rule: any, value: number) => {
          if (value <= 0) {
            return new Error('金额必须大于0')
          }
          return true
        },
        trigger: 'blur',
      },
    ],
    source: [{ required: true, message: '请输入支付方式', trigger: 'blur' }],
  })

  // 类别选项
  const categoryOptions = ref([
    { value: '餐饮', label: '餐饮' },
    { value: '交通', label: '交通' },
    { value: '购物', label: '购物' },
    { value: '娱乐', label: '娱乐' },
    { value: '住房', label: '住房' },
    { value: '其他', label: '其他' },
  ])

  // 打开对话框方法
  const openAddDialog = () => {
    console.log('尝试打开对话框')
    dialogVisible.value = true
  }

  // 关闭添加对话框方法
  const closeAddDialog = () => {
    console.log('尝试关闭对话框')
    dialogVisible.value = false
  }

  // 对话框打开时的回调
  const onDialogOpen = () => {
    console.log('对话框已打开')
    // 确保表单引用已初始化
    nextTick(() => {
      if (addFormRef.value) {
        console.log('重置表单字段')
        addFormRef.value.resetFields()
        // 设置当前用户ID
        newRecord.userId = userId.value
      } else {
        console.error('表单引用未初始化')
      }
    })
  }

  // 编辑对话框打开时的回调
  const onEditDialogOpen = () => {
    console.log('编辑对话框已打开')
    // 确保表单引用已初始化
    nextTick(() => {
      if (editFormRef.value) {
        console.log('重置编辑表单字段')
        editFormRef.value.resetFields()
        editRecord.userId = userId.value
      } else {
        console.error('编辑表单引用未初始化')
      }
    })
  }

  // 初始化
  onMounted(() => {
    console.log('组件已挂载')
    initDateOptions()
    loadUserId()
    fetchBillData()
  })

  // 初始化日期筛选
  const initDateOptions = () => {
    const options = []
    for (let i = 6; i >= 0; i--) {
      const date = new Date()
      date.setDate(date.getDate() - i)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      options.push({ text: `${year}-${month}-${day}`, value: `${year}-${month}-${day}` })
    }
    dateOptions.value = options
    console.log('日期筛选选项已初始化:', dateOptions.value)
  }

  // 加载用户ID
  const loadUserId = () => {
    const id = localStorage.getItem('userId')
    if (id) {
      userId.value = id
      console.log('用户ID已加载:', userId.value)
    } else {
      ElMessage.error('用户未登录，请先登录')
      console.error('用户ID不存在')
    }
  }

  // 获取账单数据
  const fetchBillData = async (forceRefresh = false) => {
    if (loading.value && !forceRefresh) return
    loading.value = true
    console.log('开始获取账单数据...')
    try {
      if (!userId.value) throw new Error('用户ID不存在，请重新登录')

      const response = await getBookDataList(Number(userId.value))
      tableData.value = response.map((item) => ({
        id: item.id,
        bookDate: formatDate(item.bookDate),
        category: item.category,
        description: item.remark || '无描述',
        price: item.price,
        source: item.source,
        remark: item.remark,
        type: item.type,
      }))

      console.log('获取账单数据成功，记录数:', tableData.value.length)
      if (tableData.value.length === 0) {
        ElMessage.info('暂无账单记录')
      }
    } catch (error: any) {
      console.error('获取账单数据失败:', error)
      ElMessage.error(error.message || '获取账单数据失败，请稍后再试')
    } finally {
      loading.value = false
    }
  }

  // 刷新数据
  const refreshData = () => {
    console.log('刷新数据...')
    fetchBillData(true)
  }

  // 日期格式化
  const formatDate = (dateInput: string | Date) => {
    if (!dateInput) return ''
    const date = typeof dateInput === 'string' ? new Date(dateInput) : dateInput
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  }

  // 重置筛选
  // const resetDateFilter = () => {
  //   console.log('重置日期筛选')
  //   tableRef.value?.clearFilter('bookDate' as any)
  // }

  const clearFilter = () => {
    console.log('重置所有筛选')
    tableRef.value?.clearFilter()
  }

  // 金额格式化
  const formatCurrency = (row: any) => {
    return `¥${row.price.toFixed(2)}`
  }

  // 获取类别标签类型
  const getCategoryType = (category: string): string => {
    const categoryTypes: Record<string, string> = {
      餐饮: 'primary',
      交通: 'success',
      购物: 'warning',
      娱乐: 'danger',
      住房: 'info',
      其他: 'info',
    }
    return categoryTypes[category] || 'info'
  }

  // 筛选处理
  const filterHandler = (value: string, row: any, column: TableColumnCtx<any>) => {
    const property = column.property as keyof typeof row
    return row[property] === value
  }

  const filterCategory = (value: string, row: any) => row.category === value
  const filterType = (value: number, row: any) => row.type === value

  // 删除记录（调用API）
  const handleDelete = async (row: any) => {
    if (deletingIds.value.includes(row.id)) return

    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          deletingIds.value.push(row.id)
          const success = await deleteBookRecord(row.id)

          if (success) {
            tableData.value = tableData.value.filter((item) => item.id !== row.id)
            ElMessage.success('删除成功')
            console.log('记录删除成功，ID:', row.id)
          }
        } catch (error: any) {
          console.error('删除失败:', error)
          ElMessage.error(error.message || '删除失败，请稍后再试')
        } finally {
          deletingIds.value = deletingIds.value.filter((id) => id !== row.id)
        }
      })
      .catch(() => {
        // 取消操作
        console.log('删除操作已取消')
      })
  }

  // 处理添加记录
  const handleAddRecord = async () => {
    if (isAdding.value) return

    const form = addFormRef.value
    if (!form) {
      console.error('表单引用未初始化')
      ElMessage.error('表单加载失败，请重试')
      return
    }

    console.log('开始表单验证...')
    form.validate(async (valid: boolean) => {
      if (!valid) {
        console.error('表单验证失败')
        return
      }

      try {
        isAdding.value = true
        console.log('表单验证成功，准备提交数据...')

        // 准备提交的数据
        const dataToSubmit = {
          ...newRecord,
          bookDate: `${formatDate(newRecord.bookDate)} 00:00:00`, // 格式化为后端需要的格式
          userId: Number(userId.value),
          type: String(newRecord.type), // 转为字符串类型
          price: newRecord.price ? newRecord.price.toFixed(2) : '0.00', // 转为字符串并保留两位小数
        }

        console.log('[handleAddRecord] 提交数据:', dataToSubmit)

        // 调用API
        const success = await addBookRecord(dataToSubmit)

        if (success) {
          console.log('添加记录成功')
          // 成功后刷新数据
          await fetchBillData(true)

          // 重置表单
          form.resetFields()
          closeAddDialog()

          ElMessage.success('添加成功')
        }
      } catch (error: any) {
        console.error('添加失败:', error)
        ElMessage.error(error.message || '添加失败，请稍后再试')
      } finally {
        isAdding.value = false
      }
    })
  }

  // 表格单元格点击，只有非操作列才弹编辑弹窗
  const handleCellClick = (row: any, column: any) => {
    if (column.label !== '操作') {
      editDialogVisible.value = false
      nextTick(() => {
        Object.assign(editRecord, {
          id: row.id,
          // 直接赋值字符串，el-date-picker 用 value-format="YYYY-MM-DD" 可识别
          bookDate: row.bookDate,
          userId: row.userId || userId.value,
          type: row.type,
          category: row.category,
          description: row.description,
          price: row.price,
          source: row.source,
          remark: row.remark,
        })
        editDialogVisible.value = true
      })
    }
  }

  // 关闭编辑弹窗
  const closeEditDialog = () => {
    editDialogVisible.value = false
  }

  // 编辑保存
  const handleEditRecord = async () => {
    if (isEditing.value) return
    const form = editFormRef.value
    if (!form) {
      ElMessage.error('表单加载失败，请重试')
      return
    }
    form.validate(async (valid: boolean) => {
      if (!valid) return
      try {
        isEditing.value = true
        const dataToSubmit = {
          ...editRecord,
          type: String(editRecord.type),
          price: Number(editRecord.price),
          userId: Number(userId.value),
          bookDate: new Date(editRecord.bookDate).toISOString(),
        }
        const success = await updateBookRecord(dataToSubmit)
        if (success) {
          await fetchBillData(true)
          form.resetFields()
          closeEditDialog()
          ElMessage.success('修改成功')
        }
      } catch (error: any) {
        ElMessage.error(error.message || '修改失败')
      } finally {
        isEditing.value = false
      }
    })
  }

  // 监听用户ID变化
  watch(
    () => userId.value,
    (newId) => {
      if (newId) {
        console.log('用户ID已更新:', newId)
        newRecord.userId = newId
        fetchBillData()
      }
    }
  )

  // 监听对话框显示状态
  watch(dialogVisible, (newVal) => {
    console.log('对话框状态已更新:', newVal)
    if (newVal) {
      // 对话框显示时重置表单
      nextTick(() => {
        if (addFormRef.value) {
          addFormRef.value.resetFields()
          newRecord.userId = userId.value
          console.log('对话框打开时重置表单')
        }
      })
    }
  })
</script>

<style>
  .personal-bill-container {
    padding: 20px;
  }

  .filter-buttons {
    margin-bottom: 16px;
    display: flex;
    gap: 10px;
  }

  h2 {
    margin-bottom: 20px;
    color: #333;
  }

  .loading-container {
    min-height: 300px;
  }

  .empty-data {
    text-align: center;
    padding: 40px 0;
    color: #909399;
  }
</style>
